package com.tfj.utils;

import android.content.Context;
import android.graphics.Bitmap;
import android.media.MediaMetadataRetriever;
import android.os.AsyncTask;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.HashMap;

/**
 * Created by mac on 2018/12/25.
 */

public class VideoUtil {
    public static File file;
    public static String TAG = "VideoUtil";

    /**
     * Create a file Uri for saving an image or video
     */
//    public static Uri getOutputMediaFileUri(Context context, int type) {
//        Uri uri = null;
//        //适配Android N
//        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//            return FileProvider.getUriForFile(context, context.getApplicationContext().getPackageName() + ".provider", getOutputMediaFile());
//        } else {
//            return Uri.fromFile(getOutputMediaFile());
//        }
//    }

    /**
     * Create a File for saving an image or video
     */
    public static File getOutputMediaFile(String videoPath) {
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this.
        File mediaStorageDir = new File(Environment.getExternalStoragePublicDirectory(
                Environment
                        .DIRECTORY_PICTURES), "WeWin");
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.
        // Create the storage directory if it does not exist
        if (!mediaStorageDir.exists()) {
            if (!mediaStorageDir.mkdirs()) {
                return null;
            }
        }
        // Create a media file name
        String fileName = videoPath.substring(videoPath.lastIndexOf("/") + 1,videoPath.lastIndexOf("."));
        Log.i(TAG,"fileName--->"+fileName);
        File mediaFile = new File(mediaStorageDir.getPath() + File.separator +
                "VID_" + fileName + ".jpg");
        file = mediaFile;
        return mediaFile;
    }

    /**
     * 获取视频的第一帧图片
     */
    public static void getImageForVideo(Context context,String videoPath, OnLoadVideoImageListener listener) {
        LoadVideoImageTask task = new LoadVideoImageTask(context,listener,videoPath);
        task.execute(videoPath);
    }

    public static class LoadVideoImageTask extends AsyncTask<String, Integer, File> {
        private OnLoadVideoImageListener listener;
        private String videoPath ;
        private Context context;
        public LoadVideoImageTask(Context context,OnLoadVideoImageListener listener,String videoPath) {
            this.listener = listener;
            this.videoPath = videoPath;
            this.context = context;
        }

        @Override
        protected File doInBackground(String... params) {
            MediaMetadataRetriever mmr = new MediaMetadataRetriever();
            String path = params[0];
            //获取网络视频第一帧图片
            mmr.setDataSource(path, new HashMap());
            Bitmap bitmap = mmr.getFrameAtTime();
            //保存图片
            File f = getOutputMediaFile(videoPath);
            if (f.exists()) {
                mmr.release();
                return f;
            }
            try {
                FileOutputStream out = new FileOutputStream(f);
                bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.flush();
                out.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                MediaStore.Images.Media.insertImage(context.getContentResolver(),
                        file.getAbsolutePath(),file.getName(), null);
            } catch (FileNotFoundException e) {
                Log.i(TAG, "FileNotFoundException2");
                e.printStackTrace();
            }
            mmr.release();
            return f;
        }

        @Override
        protected void onPostExecute(File file) {
            super.onPostExecute(file);
            if (listener != null) {
                listener.onLoadImage(file);
            }
        }
    }

    public interface OnLoadVideoImageListener {
        void onLoadImage(File file);
    }

}
